/**
 * Copyright 2013-2023 Xia Jun(3979434@qq.com).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 ***************************************************************************************
 *                                                                                     *
 *                        Website : http://www.farsunset.com                           *
 *                                                                                     *
 ***************************************************************************************
 */
package com.farsunset.cim.sdk.android.filter;

import java.util.List;

import com.farsunset.cim.sdk.android.common.Protocol;
import com.farsunset.cim.sdk.android.constant.CIMConstant;
import com.farsunset.cim.sdk.android.exception.AioDecodeException;
import com.farsunset.cim.sdk.android.model.HeartbeatRequest;
import com.farsunset.cim.sdk.android.model.Message;
import com.farsunset.cim.sdk.android.model.ReplyBody;
import com.farsunset.cim.sdk.android.model.proto.MessageProto;
import com.farsunset.cim.sdk.android.model.proto.ReplyBodyProto;
import com.google.protobuf.InvalidProtocolBufferException;

import android.util.Log;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

/**
 * 客户端消息解码
 */
public class ClientMessageDecoder extends ByteToMessageDecoder {
	final static String TAG = ClientMessageDecoder.class.getSimpleName();

	@Override
	protected void decode(ChannelHandlerContext arg0, ByteBuf buffer, List<Object> queue) throws Exception {

		if (buffer == null) {
			return;
		}
		buffer.markReaderIndex();
		byte version = buffer.readByte();
		if(version != Protocol.VERSION){
			return;
		}
		//标志位
		byte maskByte = buffer.readByte();
		byte cmdByte = buffer.readByte();
		int dataLength = buffer.readInt();
		int lestDataLength= buffer.readableBytes();

		// 如果消息体没有接收完整，则重置读取，等待下一次重新读取
		if (dataLength > buffer.readableBytes()) {
			buffer.resetReaderIndex();
			return;
		}
		buffer.resetReaderIndex();
		byte[] dataBytes = new byte[dataLength+7];
		buffer.readBytes(dataBytes);
		Object message = mappingMessageObject(dataBytes);
		if (message != null) {
			queue.add(message);
		}

	}

	private Object mappingMessageObject(byte[] bytes, byte type) throws InvalidProtocolBufferException {


		ByteBuffer buf = ByteBuffer.wrap(bytes);
		TcpPacket tcpPacket= null;
		try {
			tcpPacket = TcpServerDecoder.decode(buf);
		} catch (AioDecodeException e) {
			//消息处理异常
			e.printStackTrace();
			return null;
		}
		return tcpPacket;

	}

	/**
	 * 解析消息体长度
	 * 
	 * @param type
	 * @param length
	 * @return
	 */
	private int getContentLength(byte lv, byte hv) {
		int l = (lv & 0xff);
		int h = (hv & 0xff);
		return (l | (h <<= 8));
	}

	public static int bytesToInt(byte[] src, int offset) {
		int value;
		value = (int) ((src[offset] & 0xFF)
				| ((src[offset+1] & 0xFF)<<8)
				| ((src[offset+2] & 0xFF)<<16)
				| ((src[offset+3] & 0xFF)<<24));
		return value;
	}

	/**
	 * byte数组中取int数值，本方法适用于(低位在后，高位在前)的顺序。和intToBytes2（）配套使用
	 */
	public static int bytesToInt2(byte[] src, int offset) {
		int value;
		value = (int) ( ((src[offset] & 0xFF)<<24)
				|((src[offset+1] & 0xFF)<<16)
				|((src[offset+2] & 0xFF)<<8)
				|(src[offset+3] & 0xFF));
		return value;
	}

}
